package com.longfor.dragonshard.service.impl;

import com.longfor.daenerys.config.LFProperties;
import com.longfor.dragonshard.common.constant.ConfigConstants;
import com.longfor.dragonshard.common.enums.BizEnum;
import com.longfor.dragonshard.common.util.CommonUtils;
import com.longfor.dragonshard.entity.Demo;
import com.longfor.dragonshard.mapper.DemoMapper;
import com.longfor.dragonshard.service.IDemoService;
import com.longfor.dragonshard.service.IValidateService;
import com.longfor.dragonshard.service.base.AbstractBaseService;
import com.longfor.drogon.common.LFConstants;
import com.longfor.drogon.common.exception.LFBizException;
import com.longfor.drogon.common.util.LFDefaultKeyGenerator;
import com.longfor.drogon.common.util.LFIP;
import com.longfor.drogon.common.util.LFJedisUtils;
import com.longfor.drogon.common.util.LFValidateCode;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StopWatch;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;

/**
 * Validate service
 *
 * @author chi.zhang
 * @version v1.0
 * @create 2017-10-05 下午2:28
 **/
@Service
public class ValidateServiceImpl implements IValidateService {
    private Logger logger = LoggerFactory.getLogger(ValidateServiceImpl.class);

    @Autowired
    private LFProperties lfProperties;

    @Override
    public Map<String, String> getValidate(HttpServletRequest request) {
        Map<String, String> resultMap = new HashMap<>();

        String ipKey = ConfigConstants.VALIDATE.CACHE_PER_KEY_VALIDATE_IP + ConfigConstants.CACHE_SPLIT_KEY + LFIP.getClientRealip(request);
        //同IP刷新请求间隔验证
        if (lfProperties.getValidateCode().getMinInterval() > 0) {
            if (LFJedisUtils.isCached(ipKey)) {
                //获取验证码过于频繁，请稍后再试
                throw new LFBizException(BizEnum.E9903.getText());
            }
        }
        //生成验证码
        StopWatch watch = new StopWatch();
        watch.start();
        String validateKey = CommonUtils.getValidateKey();
        LFValidateCode validateCodeBean = new LFValidateCode(
                ConfigConstants.VALIDATE.VALIDATE_IMG_WIDTH,
                ConfigConstants.VALIDATE.VALIDATE_IMG_HEIGHT,
                ConfigConstants.VALIDATE.VALIDATE_IMG_CODE_COUNT,
                ConfigConstants.VALIDATE.VALIDATE_IMG_LINE_COUNT,
                ConfigConstants.VALIDATE.VALIDATE_IMG_FONT_SIZE
        );
        resultMap.put("base64ValidateImg", validateCodeBean.getBase64ValidateImg());
        resultMap.put("validateKey", validateKey);
        resultMap.put("timeLeft", lfProperties.getValidateCode().getMinInterval().toString());
        watch.stop();
        logger.debug("==== LFValidateCode - 耗时:" + watch.getTotalTimeMillis());

        //将验证码放到缓存
        LFJedisUtils.saveString(
                validateKey,
                validateCodeBean.getValidateCode(),
                lfProperties.getValidateCode().getActiveTime()
        );
        //将请求记录放到缓存
        LFJedisUtils.saveString(
                ipKey,
                ipKey,
                lfProperties.getValidateCode().getMinInterval()
        );

        logger.debug("==LF==validateCode:" + validateCodeBean.getValidateCode());
        return resultMap;
    }

    @Override
    public Boolean checkValidate(String validateKey, String validateCode) {
        if (LFJedisUtils.isCached(validateKey)) {
            String cacheCode = LFJedisUtils.getString(validateKey);
            if (!validateCode.equals(cacheCode)) {
                //删除
                LFJedisUtils.delKey(validateKey);
                //验证码错误
                throw new LFBizException(BizEnum.E9905.getText());
            }
        } else {
            //验证码已过期
            throw new LFBizException(BizEnum.E9904.getText());
        }
        //删除
        LFJedisUtils.delKey(validateKey);
        return true;
    }
}
